package billrestauration.secrity.authentication.provider;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import billrestauration.daos.ExtraDao;
import billrestauration.entities.Utilisateur;


public class AuthenticationManeger implements org.springframework.security.authentication.AuthenticationProvider {
	 private org.springframework.context.support.ReloadableResourceBundleMessageSource messageresolver;
	 
	public org.springframework.context.support.ReloadableResourceBundleMessageSource getMessageresolver() {
		return messageresolver;
	}

	public void setMessageresolver(
			org.springframework.context.support.ReloadableResourceBundleMessageSource messageresolver) {
		this.messageresolver = messageresolver;
	}

	public ExtraDao getUserservice() {
		return userservice;
	}

	public void setUserservice(ExtraDao userservice) {
		this.userservice = userservice;
	}

	public billrestauration.secrity.encoder.PasswordEncoder getEncoder() {
		return encoder;
	}

	public void setEncoder(billrestauration.secrity.encoder.PasswordEncoder encoder) {
		this.encoder = encoder;
	}

	private ExtraDao userservice;
 
private billrestauration.secrity.encoder.PasswordEncoder encoder;
 
private String  usernamenotfound="authentication.usernamenotfound";
 
private String  badcredential="authentication.badcredential";
	 
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		// TODO Auto-generated method stub
		if(null==authentication)throw new IllegalArgumentException("authentication object must not be null");
		 String username = authentication.getName();
	        String password = (String) authentication.getCredentials();
	 
	        Utilisateur user = (Utilisateur) userservice.loadUserByUsername(username);
	        if (null==user) {
	            throw new BadCredentialsException(messageresolver.getMessage(  usernamenotfound, null, Locale.FRANCE));
	        }
	        encoder.setSalt(user.getSalt());
	        password=encoder.encode(password);
	 
	        if (!(password.compareTo(user.getPassword())==0)) {
	            throw new BadCredentialsException(messageresolver.getMessage( badcredential, null, Locale.FRANCE));
	        }
	 
	        
	        return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());
	 
	}

	@Override
	public boolean supports(Class<?> authentication) {
		// TODO Auto-generated method stub
		return true;
	}

}
